package com.cyj.comment.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cyj.comment.entity.ShopType;
import com.cyj.comment.mapper.ShopTypeMapper;
import com.cyj.comment.service.ShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyj.comment.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.cyj.comment.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chixiaowai
 * @since 2023-04-04
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements ShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopTypeService shopTypeService;

    @Override
    public Result queryShopTypeList() {
        //1、从redis中查询所有商铺类型
        String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        //2、存在就返回
        if (!StrUtil.isBlank(shopTypeJson)){
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypes);
        }
        //3、不存在去查询数据库
        List<ShopType> shopTypeList = shopTypeService.list();
        if(shopTypeList == null){
            return Result.fail("分类不存在");
        }
        //4、将从数据库查到的商铺类型存入redis中
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList), CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        //5、返回
        return Result.ok(shopTypeList);
    }
}
